﻿//
// Copyright (c) 2011 HyperCrunch, Inc. http://www.hypercrunch.com 
// Author: Nik Kalyani  http://www.kalyani.com (Twitter: @techbubble)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web;
using System.Text;
using System.Collections;

using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.ClientCapability;
using DotNetNuke.Web.Client.ClientResourceManagement;

namespace HyperCrunch.Druid
{
    public class DruidHttpModule : IHttpModule
    {
        UIContext uiContext = null;
        bool skipProcessing = false;

        public static string ModuleName
        {
            get
            {
                return ("DruidHttpModule");
            }
        }

        public void Init(HttpApplication app)
        {
            app.PostAuthenticateRequest += new EventHandler(App_PostAuthenticateRequest);  
            app.PreRequestHandlerExecute += new EventHandler(App_PreRequestHandlerExecute);
        }

        void App_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            skipProcessing = SkipRequestProcessing(context);
            if (skipProcessing) return;

            uiContext = new UIContext(context);
            uiContext.Debug = context.IsDebuggingEnabled;

            RuleProcessingResultType result = RuleEngine.Process(uiContext);

            // If the rule engine enumeration requires a custom response
            // then flush the output that was generated and complete the request
            if (result == RuleProcessingResultType.RenderCustomResponse)
            {
                //WriteDebugText(context.Response);
                context.Response.Flush();
                uiContext.Context.ApplicationInstance.CompleteRequest();
            }
        }

        void App_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            if (skipProcessing) return;
            try
            {
                Page page = HttpContext.Current.Handler as Page;
                page.PreRender += new EventHandler(Page_PreRender);
                page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
            }
            catch
            {
                // Custom handler so nothing to do
            }
        }

        void Page_PreRender(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Page page = context.Handler as Page;
            Control body = page.FindControl("body");

            int counter = 999900;
            foreach(string stylesheetUrl in uiContext.StylesheetUrls)
            {
                var url = Globals.ResolveUrl(uiContext, stylesheetUrl);
                ClientResourceManager.RegisterStyleSheet(page, url, counter++);
            }

            counter = 999900;
            foreach (string scriptUrl in uiContext.ScriptUrls)
            {
                var url = Globals.ResolveUrl(uiContext, scriptUrl);
                ClientResourceManager.RegisterScript(page, url, counter++);
            }
        }


        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Page page = context.Handler as Page;
            Control body = page.FindControl("body");

            if (uiContext.ContentModifiers.Count > 0)
            {
                for (int c = 0; c < uiContext.ContentModifiers.Count; c++)
                {
                    string contentModifier = Globals.ResolveUrl(uiContext, uiContext.ContentModifiers[c]);
                    if (contentModifier.IndexOf(".") == -1)
                        contentModifier = "HyperCrunch.Druid.ContentModifiers." + contentModifier + "ContentModifier";

                    IContentModifier renderer = (IContentModifier)DataCache.GetCache(contentModifier);
                    if (renderer == null)
                    {
                        Type rendererType = Type.GetType(contentModifier);
                        if ((rendererType != null) && (typeof(IContentModifier).IsAssignableFrom(rendererType)))
                        {
                            renderer = (IContentModifier)Activator.CreateInstance(rendererType);
                            if (renderer != null)
                                DataCache.SetCache(contentModifier, renderer);
                        }
                    }

                    if (renderer != null)
                        renderer.RenderContent(uiContext, page);
                }
            }

            if (uiContext.Debug)
            {
                Literal debug = new Literal();
                debug.Text = uiContext.LogText;
                if (body != null)
                    body.Controls.Add(debug);
            }
        }

        private static bool SkipRequestProcessing(HttpContext context)
        {
            if (context == null) return true;
            HttpRequest request = context.Request;

            if (request.Headers["x-microsoftajax"] != null) return true;

            string url = request.Url.LocalPath.ToLower();
            /*
            if (url.Contains(Globals.HANDLER_SCRIPT_NAME))
            {
                if (context.Request.QueryString[Globals.RESOURCE_PARAMETER_NAME] != null)
                    RequestManager.StreamResource(context);
                return true;
            }
            */
            
            if (
                    url.Contains("install.aspx") ||
                    url.Contains("installwizard.aspx") ||
                    url.Contains("upgradewizard.aspx") ||
                    url.Contains(".asmx") ||
                    url.Contains(".axd") ||
                    url.Contains(".ashx") ||
                    (request.QueryString["popup"] != null)
                )

                return true;

            return false;
        }

        public void Dispose()
        {
        }
    }
}
